using Godot;
using Godot.Collections;
using System;

public partial class MapManager : Node2D
{
	[Export]
	public Array<string> Maps = new Array<string>();
	public Array<string> instancedMap = new Array<string>();
	private Map _map;
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		instancedMap.Add("home");
		//AddMap("home",Vector2.Zero)
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
		foreach(Map map in GetChildren())
		{
			map.Update(delta);
		}
	}

	public bool AddMap(string mapname ,Vector2 pos, int idFrom ,string mapFrom)
	{
		//判定是否在特定任务中，只能开特定地图
		//mapname = SpecialTask(mapname);
		int idTo = 0;
		switch (idFrom)
		{
			case 1:
			idTo = 3;
			break;
			case 2:
			idTo = 4;
			break;
			case 3:
			idTo = 1;
			break;
			case 4:
			idTo = 2;
			break;
		}
		var children = this.GetChildren();
		foreach (var child in children)
		{
			//GD.Print(child.Name);
			if (child.Name.ToString().ToLower() == mapname)
			{return false;}
		}
		string basepath = "res://scences/";
		string path = basepath + mapname + ".tscn";
		var Game = GetNode<Game>("/root/Game");
		Map newmap= Game.InstantScene(path) as Map;
		var splices = newmap.GetChildren();
		foreach (var child in splices)
		{
			if(child is Splice)
			{
				Splice splice = child as Splice;
				if(splice.id == idTo)
				{
					splice.mapname = mapFrom;
				}
			}
		}
		newmap.Position = pos;
		this.AddChild(newmap);
		instancedMap.Add(mapname);
		//newmap.Dispose();
		return true;
	}

	public bool RemoveMap(string mapname)
	{
		var children = this.GetChildren();
		if (children.Count == 1)
		{return false; }
		foreach (var child in children)
		{
			Map map = child as Map;
			if(map.Name.ToString().ToLower() == mapname)
			{
				if(!map.IsSafe)
				{
					var UIControl = GetNode<UIControl>("/root/UIControl");
					UIControl.GetGuiViewManager().ShowTips("该房间未收容成功，无法收起。");
					return false;
				}
				map.QueueFree();
				instancedMap.Remove(mapname);
			}
		}
		return true;
	}

	public bool HasMap(string mapname)
	{
		var children = this.GetChildren();
		foreach (var child in children)
		{
			Map map = child as Map;
			if(map.MapEnemiesData.name == mapname)
			{return true;}
		}
		return false;
	}

	public string SpecialTask(string mapname)
	{
		var Game = GetNode<Game>("/root/Game");
		TaskManager _taskManager = Game.get_player().GetNode<TaskManager>("%TaskManager");
		foreach(Tasks child in _taskManager.runningTasks)
		{
			if(child.name =="")
			{
				mapname = "";
			}
		}
		return mapname;
	}
}
